package com.situ.supermarket.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//专门管是否登陆的过滤器
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String uri = req.getRequestURI();//当前的请求地址
        boolean isLogin = req.getSession().getAttribute("currentUser")!=null;
        if (isLogin || uri.equals("/login") || uri.startsWith("/js/") || uri.startsWith("/images/") || uri.startsWith("/lib/") || uri.startsWith("/css/")){
            filterChain.doFilter(servletRequest,servletResponse);//很重要      这行代码上边的是请求进来时执行的，下边是往回返时执行的

        }else {
            HttpServletResponse resp = (HttpServletResponse) servletResponse;
            resp.sendRedirect("/login");
        }
    }
}
